// @flow
import React from 'react'
import styles from './Login.css'
import { Form, Icon, Input, Button, Checkbox } from 'antd'
import universalFetch, { LoginFetch, handleFetchError } from 'store/modules/fetch'
import { saveUserId } from 'store/modules/user'
import { saveUserMenu } from 'store/modules/menu'
import { connect } from 'react-redux'
import md5 from 'md5'

const FormItem = Form.Item
type Props = {
  saveUserId: Function,
  saveUserMenu: Function,
  form: Object,
  history: Object
}
type State = {
  errorMes: string
}
class Login extends React.Component {
  props: Props
  state: State
  errorMesFun: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      errorMes: ''
    }
    this.errorMesFun = this.errorMesFun.bind(this)
  }
  componentWillMount () {
    // 判断token是否清除，没有清楚直接跳到首页（设备档案）
    const token = localStorage.getItem('asset_token')
    if (token) {
      this.props.history.push('/device')
    }
  }
  errorMesFun = (rule, value, callback) => {
    this.setState({
      errorMes: ''
    })
    callback()
  }
  handleSubmit = (e) => {
    const { saveUserId } = this.props
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values['password'] = md5(values['password'])
        LoginFetch(`${__SERVICE_API__}login`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(values)
        })
          .then(res => {
            return res.json()
          })
          .then((json) => {
            if (json.code === 400103) {
              this.setState({
                errorMes: '用户名或密码不正确'
              })
            } if (json.code === 400104) {
              this.setState({
                errorMes: '用户没有登陆权限'
              })
            } if (json.code === 200000) {
              this.setState({
                errorMes: ''
              })
              const result = json.result
              saveUserId(result.userId)
              localStorage.setItem('asset_token', result.accessToken)
              this.getUserMenu(result.userId)
            }
          })
          .catch((err) => {
            console.error(err)
          })
      }
    })
  }

  getUserMenu (userId: number) {
    const { saveUserMenu } = this.props
    universalFetch(`${__SERVICE_API__}sys/users/${userId}/menus?isTree=true&pageNum=1&pageSize=1000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        saveUserMenu(json.result)
        this.props.history.push('/')
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { errorMes } = this.state
    return (
      <div className={styles['loginbg']} >
        <div className={styles['loginbg_fixed']} />
        <div className={styles['logincon']}>
          <div className={styles['con']}>
            <h3 className={styles['title']}>设备远程运维管理系统</h3>
            <Form onSubmit={this.handleSubmit} className={styles['loginForm']}>
              <FormItem>
                {getFieldDecorator('username', {
                  rules: [{ required: true, message: '请输入用户名!', whitespace: true }, {
                    validator: this.errorMesFun
                  }]
                })(
                  <Input prefix={<Icon type='user' style={{ fontSize: 13 }} />} placeholder='用户名' />
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator('password', {
                  rules: [{ required: true, message: '请输入密码!' }, {
                    validator: this.errorMesFun
                  }]
                })(
                  <Input
                    prefix={<Icon type='lock'style={{ fontSize: 13 }} />}
                    type='password'
                    placeholder='密码' />
                )}
              </FormItem>
              <FormItem style={{ color: '#bbbbbb', marginTop: -10 }}>
                {getFieldDecorator('remember', {
                  valuePropName: 'checked',
                  initialValue: false
                })(
                  <Checkbox>记住我（公共场所慎用）</Checkbox>
                )}
                <span className={styles['errorMes']}>{errorMes}</span>
              </FormItem>
              <FormItem className={styles['loginBtncon']}>
                <Button type='primary' size='large' htmlType='submit' className={styles['loginBtn']}>
                  登录
                </Button>
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {}
}
export default connect(mapStatesToProps, { saveUserId, saveUserMenu })(Form.create({})(Login))
